package arrays

import "gitee.com/baizhige/go-server-tempalte/util/assert"

//数组类工具

func For[T any](arr []T, peek peek[T]) {
	if assert.ArrayIsEmpty(arr) {
		return
	}
	for _, item := range arr {
		peek(item)
	}
}

func ArrToMap[K comparable, V any](arr []V, fun key[K, V]) map[K]V {
	res := make(map[K]V)
	if assert.ArrayIsEmpty(arr) {
		return res
	}
	for _, item := range arr {
		res[fun(item)] = item
	}
	return res
}

func RemoveDuplicates[T comparable](arr []T) []T {
	res := arr[:0]
	toMap := ArrToMap(arr, func(item T) T {
		return item
	})
	for key, _ := range toMap {
		res = append(res, key)
	}
	return res
}

func ArrToArr[T1 any, T2 any](arr []T1, fun covert[T1, T2]) []T2 {
	if assert.ArrayIsEmpty(arr) {
		return make([]T2, 0)
	}
	res := make([]T2, 0, len(arr))
	for _, item := range arr {
		res = append(res, fun(item))
	}
	return res
}

func Sub[T comparable](arr1 []T, arr2 []T) (res []T) {
	if assert.ArrayIsEmpty(arr1) {
		return make([]T, 0)
	}
	if assert.ArrayIsEmpty(arr2) {
		return arr1
	}
	res = make([]T, 0)

	arr2Map := make(map[T]bool, len(arr2))
	for _, j := range arr2 {
		arr2Map[j] = true
	}

	for _, i := range arr1 {
		if ok := arr2Map[i]; ok {
			continue
		}
		res = append(res, i)
	}
	return
}

// Filter 元素过滤 true保存 false过滤
func Filter[T any](arr []T, filter func(item T) bool) []T {
	res := arr[:0]
	for _, one := range arr {
		if filter(one) {
			res = append(res, one)
		}
	}
	return res
}

type peek[T any] func(item T)

type key[K comparable, V any] func(item V) K

type covert[T1 any, T2 any] func(item T1) T2
